package com.keepers.repair.service;

import com.keepers.repair.net.LogUtil;
import com.keepers.repair.tcp.BaseRecParse;
import com.keepers.repair.utils.UtilsKt;

import java.util.ArrayList;
import java.util.List;

/**
 * auth aboom
 * date 2018/11/10
 */
public class MyRecParse extends BaseRecParse<String> {

    //10 最后一个字符  13
    private int query(byte[] baseData, int data) {
        if (baseData[data] == 10) {
            return data;
        } else {
            data--;
            return data == 0 ? 0 : query(baseData, data);
        }
    }

    @Override
    public List<String> parse() {
        List<String> list = new ArrayList<>();
        byte[] baseData = getBaseData();
//        LogUtil.e(new String(baseData) + "  ---- length " + baseData.length);
        int removeSize = 0;
        try {
            int dataLen = query(baseData, baseData.length - 1);
            if (dataLen != 0) {
                for (int i = 0; i < baseData.length; i++) {
                    if (baseData[i] == '@' && baseData[i + 1] == '@') {
                        //然后两个字节是数据长度
                        if (baseData.length - i + 1 > dataLen) {//说明数据完整
                            byte[] recData = new byte[dataLen];
                            System.arraycopy(baseData, i, recData, 0, dataLen);
                            i += dataLen - 1;
                            removeSize += dataLen;
                            String s = new String(recData);
                            String[] split = s.split("\r\n");
                            for (String s1 : split) {
                                String msg = UtilsKt.decodeBase64(s1);
                                LogUtil.e("size = " + split.length + "接收的数据：" + msg);
                                list.add(msg);
                            }
                        } else {
                            LogUtil.e("parse: nonono完整的数据");
                            break;//如果长度不足 就等着
                        }
                    } else {
                        removeSize++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("数据解析错误... e = " + e.getMessage());
        }
        notifyLeftData(removeSize);
        return list;
    }
}
